package com.example.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.pojo.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class ImgController {
    @Value("${reggie.basePath}")
    private String basePath;
    private String endpoint="https://oss-cn-nanjing.aliyuncs.com";
    @Value("${aliyun.oss.ID}")
    private String accessKeyID;
    //="LTAI5tRKRVPxtStrna6FGuYm";
    @Value("${aliyun.oss.PASSWORD}")
    private String accessKeySecret;
    //="fOJESmompFEQ6cBTzTylIlKRGGUx5V";
    private String bucketName="hbnu-busnews";


    @GetMapping("/download")
    public void download(String name, HttpServletResponse hsr) throws IOException {
        String sub = name.substring(name.lastIndexOf("."));
        hsr.setContentType("image/"+sub);
        FileInputStream fis=new FileInputStream(basePath+name);
        ServletOutputStream os = hsr.getOutputStream();
        int len;
        byte[] bytes=new byte[1024];
        while((len=fis.read(bytes))!=-1){
            os.write(bytes,0,len);
            os.flush();
        }
        os.close();
        fis.close();
    }
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        log.info("上传图片,参数: {}",originalFilename);
        String sub = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("\\.","");
        /*File f=new File(basePath);
        if (!f.exists())
        {
            f.mkdirs();
        }*/
        String path = uuid + sub;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
        ossClient.putObject(bucketName,path,inputStream);
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+path;
        log.info("{}",url);
        return Result.succeed(url);
    }
}
